package org.leumasjaffe.initiativeTracker.distributed.controller;

import static org.leumasjaffe.initiativeTracker.operator.InitiativeController.tracker;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.leumasjaffe.initiativeTracker.operator.CharacterLinker;
import org.leumasjaffe.initiativeTracker.operator.InitiativeController;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;

import edu.wpi.heineman.xml.Message;
import edu.wpi.heineman.client.IMessageHandler;

@NonNullByDefault
public class KillHandler implements IMessageHandler {

	@Override
	public void process(Message response) {
		NodeList nl = response.contents.getFirstChild().getChildNodes();
		
		@SuppressWarnings("null")
		InitiativeController tracker = tracker(response.contents.getFirstChild().getAttributes()
				.getNamedItem("game").getNodeValue());

		int count = 0;
		for (int i = 0; i < nl.getLength(); i++) {
			NamedNodeMap map = nl.item(0).getAttributes();
			
			int id = Integer.decode(map.getNamedItem("id").getNodeValue());
			
			CharacterLinker c = tracker.list.lookup(id);
			c.tearDown();
			System.out.println(c.getCharacter().getName() + " has perished!");
			tracker.list.remove(c);
			count++;
			tracker.root.addDeath(i-count);
			c = null;
		}
		
		tracker.root.rebuild();		
	}

	@Override
	public IMessageHandler newCopy() {
		return new KillHandler();
	}

}
